package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.AvailableRoom;
import model.Booking;
import model.Reservation;
import model.Room;
import model.RoomHasBooking;
import model.RoomType;
import model.User;
import dao.impl.AvailableRoomDaoImpl;
import dao.impl.BookingDaoImpl;
import dao.impl.RoomDaoImpl;
import dao.impl.RoomHasBookingDaoImpl;
import dao.impl.RoomTypeDaoImpl;
import dao.impl.UserDaoImpl;
import dao.intf.BookingDao;
import dao.intf.RoomDao;
import dao.intf.RoomHasBookingDao;
import dao.intf.RoomTypeDao;
import dao.intf.UserDao;

/**
 * Servlet implementation class BookingServlet
 */
@WebServlet("/BookingServlet")
public class BookingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		RequestDispatcher dispatcher = request.getRequestDispatcher("/search.jsp");
		dispatcher.forward(request,response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if(request.getParameter("checkrates")!=null && request.getParameter("checkrates").equals("1") )
		{
			
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Availability");
			dispatcher.forward(request,response);
		}
		
		String action = "";
		if (request.getParameter("action") != null)
			action = request.getParameter("action");
		//System.out.println("action " + action);
		
		if (action.equals("edit"))
		{
			editBooking(request,response);
			
			
		}else if (action.equals("new"))
		{
			makeBooking(request,response);
		}
		else if (action.equals("delete"))
		{
			deleteBooking(request,response);
		}
		else if (action.equals("search"))
		{
			//System.out.println("search");
			searchBooking(request,response);
		}
		
		 
	}
	
	
	public void makeBooking(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		Booking booking= new Booking();
		int numberOfUnits=0;
		//booking.getStart(request.getParameter("startDate"));
		
		String firstName = "";
		String lastName = "";
		String email = "";
		String contactNo = "";
		String address = "";
		String status="";
		
		if(request.getParameter("firstName") != null)
			firstName = request.getParameter("firstName");
		if(request.getParameter("lastName") != null)  
			lastName = request.getParameter("lastName"); 
		if(request.getParameter("email") != null) 
			email = request.getParameter("email");
		if(request.getParameter("phone") != null) 
			contactNo = request.getParameter("phone");
		if(request.getParameter("address") != null) 
			address = request.getParameter("address");
		  
		  ArrayList error=new ArrayList();
		  
		  UserDao userDao=new UserDaoImpl();
		  RoomDao roomDao=new RoomDaoImpl();
		  BookingDao bookingDao=new BookingDaoImpl();
		  RoomHasBookingDao roomHasBookingDao=new RoomHasBookingDaoImpl();
		  RoomTypeDao roomTypeDao=new RoomTypeDaoImpl();
		  int duration=0;
		  int adults=0;
		  int children=0;
		 User user= userDao.getUserByEmail(email);
		 int userId=0;
		 if(user.getId()==null || user.getId()=="")
		 {
			 user.setContactNo(address);
			 user.setEmail(email);
			 user.setFirstName(firstName);
			 user.setLastName(lastName);
			 user.setContactNo(contactNo);
			 user.setAddress(address);
			 userId=userDao.saveUser(user);
		 }else
		 {
			 user.setContactNo(address);
			 user.setEmail(email);
			 user.setFirstName(firstName);
			 user.setLastName(lastName);
			 user.setContactNo(contactNo);
			 user.setAddress(address);
			 userDao.updateUser(user, email);
			 userId=Integer.parseInt(user.getId());
		 }
		  String start=request.getParameter("startDate");
		  String end=request.getParameter("endDate");
		  try{
			  if(request.getParameter("duration") != null)
				  duration=Integer.parseInt(request.getParameter("duration"));
		  }catch(Exception ex){}
		   try{
			   if(request.getParameter("adults") != null)
				   adults=Integer.parseInt(request.getParameter("adults"));
		   }catch(Exception ex){}
		   try{
			   if(request.getParameter("child") != null)
			   		children=Integer.parseInt(request.getParameter("child"));
		   }catch(Exception ex){}
		   
		   String roomStr= "";
		   if(request.getParameter("roomType") != null)
			   roomStr=request.getParameter("roomType");
		  DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
          Date startDate=new Date();
		  final Calendar calStartDate = Calendar.getInstance();
		try {
			startDate = formatter.parse(start);
			
		         try {
		        	 calStartDate.setTime(startDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		Date endDate=new Date();
		 final Calendar calEndDate = Calendar.getInstance();
		try {
			endDate = formatter.parse(end);
			 
		         try {
		        	 calEndDate.setTime(endDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		
		  try{
			  if(request.getParameter("numberOfUnits") != null)
			  		numberOfUnits=Integer.parseInt(request.getParameter("numberOfUnits"));
		  }catch(Exception ex){}
		  //Release expired Booking room
		  List<Room> roomRelease=roomDao.getExpiredRoom();
		  String roomListString="";
		
		  for (Iterator<Room> iterator = roomRelease.iterator(); iterator
					.hasNext();) {
			  
			  Room room = iterator.next();
				if(roomListString.equals(""))
				{
					roomListString +="'"+room.getRoomId()+"'";
				}else
				{
					roomListString +=",'"+room.getRoomId()+"'";
				}
			  roomDao.updateRoomStatus(roomListString, "A");
			  RoomType roomTypeRelease=roomTypeDao.getRoomTypeById(room.getTypeId());
			  roomTypeDao.updateNoofRooms(room.getTypeId(), roomTypeRelease.getNoOfRooms()+1);
			  
		  }
		  //Get Available rooms
		  List<Room> roomList=roomDao.getRoom(roomStr,"");
		  if(roomList.size()>= numberOfUnits)
		  {
			 RoomType roomType= roomTypeDao.getRoomDiscount(roomStr, duration);
			 Double totalPaid=0.0;
			 Double rate=0.0;
			   roomListString="";
			  ArrayList roomListArray=new ArrayList();
			  	  int i=0;
				  for (Iterator<Room> iterator = roomList.iterator(); iterator
						.hasNext();) {
					  if (i<numberOfUnits)
					  { rate+=roomType.getRate();
						Room room = iterator.next();
						if(roomListString.equals(""))
						{
							roomListString +="'"+room.getRoomId()+"'";
						}else
						{
							roomListString +=",'"+room.getRoomId()+"'";
						}
						roomListArray.add(room.getRoomId());
						 i++;
					
					  }else {break;}
					  roomTypeDao.updateNoofRooms(roomType.getId(), roomType.getNoOfRooms()-i);
				  }
					roomDao.updateRoomStatus(roomListString, "R");
					Double discountAmount=((rate*duration)*(Double.parseDouble(roomType.getDiscountPercent()+""))/100);	totalPaid=(rate*duration)-discountAmount;
					booking.setAdults(adults);
					booking.setChildren(children);
					booking.setStart(calStartDate.getTime());
					booking.setEnd(calEndDate.getTime());
					booking.setDuration(duration);
					booking.setTotalPaid(totalPaid);
					booking.setCreateDate(new Date());
					booking.setCreatedBy(user.getId());
					booking.setUpdateDate(new Date());
					booking.setUpdatedBy(user.getId());
					booking.setUserId(user.getId());
					booking.setBookingStatus("A");
					booking.setNumberofUnits(numberOfUnits+"");
					booking.setRoomType(roomType.getId());
					booking.setRoomTypeName(roomType.getName());
					
					//booking.setId((Integer.parseInt(bookingDao.getMaxbookingId())+1)+"-"+booking.getRoomType()+"-"+new SimpleDateFormat("yyyyMMdd").format(booking.getStart())+"-"+new SimpleDateFormat("HHmmss").format(booking.getCreateDate()));
					System.out.println("bookingDao.getMaxbookingId() " + bookingDao.getMaxbookingId());
					booking.setId((Integer.parseInt(bookingDao.getMaxbookingId())+1)+"-"+booking.getRoomType()+"-"+new SimpleDateFormat("yyyyMMdd").format(booking.getStart())+"-"+new SimpleDateFormat("HHmmss").format(booking.getCreateDate()));
					int recordCount= bookingDao.saveBooking(booking);
					if(recordCount>0)
					{
						for(int j=0;j<roomListArray.size();j++)
						{
							RoomHasBooking roomHasBooking=new RoomHasBooking();
							roomHasBooking.setBookingId(booking.getId());
							roomHasBooking.setRoomId(roomListArray.get(j).toString());
							roomHasBookingDao.saveRoomHasBooking(roomHasBooking);
							
						}
						
					}else
					{
						error.add("Booking is not successful");
					}
					RequestDispatcher rd = request.getRequestDispatcher("/reserve.jsp");
					Reservation reservation=new Reservation();//add content to obj
					reservation.setBooking(booking);
					reservation.setUser(user);
					reservation.setError(error);
					reservation.setStatus(1);
					request.setAttribute("reservation",reservation);
					rd.forward(request, response);
					
			  }else
			  {		error.add("Booking is not successful");
					RequestDispatcher rd = request.getRequestDispatcher("/reserve.jsp");
					Reservation reservation=new Reservation();//add content to obj
					reservation.setBooking(booking);
					reservation.setUser(user);
					reservation.setError(error);
					request.setAttribute("reservation",reservation);
					rd.forward(request, response);
				  
			  }
		
		
	}
	public void editBooking(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		Booking booking= new Booking();
		int numberOfUnits=0;
		//booking.getStart(request.getParameter("startDate"));
		  String bookingId = request.getParameter("bookingId");
		  String start=request.getParameter("startDate");
		  String end=request.getParameter("endDate");
		  String email = request.getParameter("email");
		  
		  //bookingId="8PRE-20130503-035710";
		  //start="2013-05-12";
		  //end="2013-06-15";
		  //email="mayzin.ice@gmail.com";
		  
		  String status="";
		  ArrayList error=new ArrayList();
		  int duration=0;
		  try{
			  if(request.getParameter("duration") != null)
				  duration = Integer.parseInt(request.getParameter("duration"));
			  }catch(Exception ex){}
		  UserDao userDao=new UserDaoImpl();
		  RoomDao roomDao=new RoomDaoImpl();
		  BookingDao bookingDao=new BookingDaoImpl();
		  RoomHasBookingDao roomHasBookingDao=new RoomHasBookingDaoImpl();
		  RoomTypeDao roomTypeDao=new RoomTypeDaoImpl();
		  User user= userDao.getUserByEmail(email);
		  booking=bookingDao.getBookingById(bookingId);
		  String roomStr=request.getParameter("roomType");
		  DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
          Date startDate=new Date();
		  final Calendar calStartDate = Calendar.getInstance();
		try {
			startDate = formatter.parse(start);
			
		         try {
		        	 calStartDate.setTime(startDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		Date endDate=new Date();
		 final Calendar calEndDate = Calendar.getInstance();
		try {
			endDate = formatter.parse(end);
			 
		         try {
		        	 calEndDate.setTime(endDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		
		 try{
			  numberOfUnits=Integer.parseInt(request.getParameter("numberOfUnits"));
		  }catch(Exception ex){}
		 
			 RoomType roomType= roomTypeDao.getRoomDiscount(roomStr, duration);
			 Double totalPaid=0.0;
			 Double rate=0.0;
			  String roomListString="";
			  ArrayList roomListArray=new ArrayList();
			  	  	 for(int i=0;i<numberOfUnits;i++)
					  { rate+=roomType.getRate();
					  }
				  
			  		Double discountAmount=((rate*duration)*(Double.parseDouble(roomType.getDiscountPercent()+""))/100);totalPaid=(rate*duration)-discountAmount;
					booking.setStart(calStartDate.getTime());
					booking.setEnd(calEndDate.getTime());
					booking.setDuration(duration);
					booking.setTotalPaid(totalPaid);
					booking.setCreateDate(new Date());
					booking.setUpdateDate(new Date());
					booking.setBookingStatus("A");
					booking.setNumberofUnits(numberOfUnits+"");
					booking.setRoomType(roomType.getId());
					booking.setRoomTypeName(roomType.getName());

					int recordCount=bookingDao.updateBooking(booking);
					if(recordCount>0)
					{
						RequestDispatcher rd = request.getRequestDispatcher("/reserve.jsp");
						Reservation reservation=new Reservation();//add content to obj
						reservation.setBooking(booking);
						reservation.setUser(user);
						reservation.setError(error);
						reservation.setStatus(2);
						request.setAttribute("reservation",reservation);
						rd.forward(request, response);
						
					}else
					{
						error.add("Booking is not successful");
						RequestDispatcher rd = request.getRequestDispatcher("/reserve.jsp");
						Reservation reservation=new Reservation();//add content to obj
						reservation.setBooking(booking);
						reservation.setUser(user);
						reservation.setError(error);
						request.setAttribute("reservation",reservation);
						rd.forward(request, response);
					  
					}
	}
	public void deleteBooking(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		
		Booking booking= new Booking();
		int numberOfUnits=0;
		//booking.getStart(request.getParameter("startDate"));
		  String bookingId = request.getParameter("bookingId");
		  String start=request.getParameter("startDate");
		  String end=request.getParameter("endDate");
		  String email = request.getParameter("email");
		  
		  //bookingId="8PRE-20130503-035710";
		  //start="2013-05-12";
		  //end="2013-06-15";
		  //email="mayzin.ice@gmail.com";
		  
		  String status="";
		  ArrayList error=new ArrayList();
		  int duration=0;
		  try{
			   duration=Integer.parseInt(request.getParameter("duration"));
			  }catch(Exception ex){}
		  UserDao userDao=new UserDaoImpl();
		  RoomDao roomDao=new RoomDaoImpl();
		  BookingDao bookingDao=new BookingDaoImpl();
		  RoomHasBookingDao roomHasBookingDao=new RoomHasBookingDaoImpl();
		  RoomTypeDao roomTypeDao=new RoomTypeDaoImpl();
		  User user= userDao.getUserByEmail(email);
		  booking=bookingDao.getBookingById(bookingId);
		  String roomStr=request.getParameter("roomType");
		  DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
          Date startDate=new Date();
		  final Calendar calStartDate = Calendar.getInstance();
		try {
			startDate = formatter.parse(start);
			
		         try {
		        	 calStartDate.setTime(startDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		Date endDate=new Date();
		 final Calendar calEndDate = Calendar.getInstance();
		try {
			endDate = formatter.parse(end);
			 
		         try {
		        	 calEndDate.setTime(endDate);
		            
		         } 
		         catch (Exception e) {
		             e.printStackTrace();
		         }
		} catch (Exception e) {
			e.printStackTrace();
		}  
		
		 try{
			  numberOfUnits=Integer.parseInt(request.getParameter("numberOfUnits"));
		  }catch(Exception ex){}
		 
			 RoomType roomType= roomTypeDao.getRoomDiscount(roomStr, duration);
			 Double totalPaid=0.0;
			 Double rate=0.0;
			  String roomListString="";
			  ArrayList roomListArray=new ArrayList();
			  	  	 for(int i=0;i<numberOfUnits;i++)
					  { rate+=roomType.getRate();
					  }
			  	   RoomType roomTypeRelease=roomTypeDao.getRoomTypeById(roomStr);
					  roomTypeDao.updateNoofRooms(roomStr, roomTypeRelease.getNoOfRooms()-numberOfUnits);
			  		Double discountAmount=((rate*duration)*(Double.parseDouble(roomType.getDiscountPercent()+""))/100);totalPaid=(rate*duration)-discountAmount;
					booking.setStart(calStartDate.getTime());
					booking.setEnd(calEndDate.getTime());
					booking.setDuration(duration);
					booking.setTotalPaid(totalPaid);
					booking.setCreateDate(new Date());
					booking.setUpdateDate(new Date());
					booking.setBookingStatus("C");
					booking.setNumberofUnits(numberOfUnits+"");
					booking.setRoomType(roomType.getId());
					booking.setRoomTypeName(roomType.getName());

					int recordCount=bookingDao.updateBooking(booking);
					if(recordCount>0)
					{
						RequestDispatcher rd = request.getRequestDispatcher("/reserve.jsp");
						Reservation reservation=new Reservation();//add content to obj
						reservation.setBooking(booking);
						reservation.setUser(user);
						reservation.setError(error);
						reservation.setStatus(3);
						request.setAttribute("reservation",reservation);
						rd.forward(request, response);
						
					}else
					{
						error.add("Cancellation is not successful");
						RequestDispatcher rd = request.getRequestDispatcher("/reserve.jsp");
						Reservation reservation=new Reservation();//add content to obj
						reservation.setBooking(booking);
						reservation.setUser(user);
						reservation.setError(error);
						request.setAttribute("reservation",reservation);
						rd.forward(request, response);
					}
		}
	
	public void searchBooking(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
			
		PrintWriter out = response.getWriter();		
		response.setContentType("text/HTML");
		
		  //out.println("search booking ....");
		  String bookingNo = request.getParameter("bookingno");
		  String email = request.getParameter("bookingemail");
		  
		  List<Booking> bookingList = new ArrayList<Booking>();														
			BookingDaoImpl bookingDaoObj = new dao.impl.BookingDaoImpl();	
			
			bookingList = bookingDaoObj.getBookingItems(email, bookingNo);
			//out.println(" booking List : " + bookingList.size() + "");
			
			request.setAttribute("bookinglist", bookingList);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/search.jsp");
			dispatcher.forward(request,response);	
		  
		  //bookingId="8PRE-20130503-035710";
		  //start="2013-05-12";
		  //end="2013-06-15";
		  //email="mayzin.ice@gmail.com";
		  
		 
		
	}
}
	
